package com.ihcy.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName 继承 HandlerInterceptorAdapter
 * @Description
 * @Author ihcy
 * @Date 2019/12/11 10:09
 * @Version 1.0
 **/
public class MyInterceptor2 extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("startTime",System.currentTimeMillis());
        System.out.println("============== MyInterceptor2 preHandle============== ");
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("============== MyInterceptor2 postHandle " +
                "cost time" +(System.currentTimeMillis()-(Long)request.getAttribute("startTime"))+
                "============== ");
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        request.removeAttribute("startTime");
        System.out.println("============== MyInterceptor2 afterCompletion============== ");
        super.afterCompletion(request, response, handler, ex);
    }

    /**
     * 如果返回一个concurrent类型的变量，会启用一个新的线程。
     * 执行完preHandle方法之后立即会调用afterConcurrentHandlingStarted,
     * 然后新线程再以次执行拦截器(等效于中心发起一个链接的拦截器流程)
     *
     */
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("============== MyInterceptor2 afterConcurrentHandlingStarted============== ");
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
